<html>
	<head>
		<title>Editor {{nome}}</title>
		<link href="/css/style.css" rel="stylesheet" type="text/css">
    </head>
	<body>
        <div class="wrapper">
            <div class="page">
                <div class="main-container col1-layout">
                    <div class="header-container"> </div>
                    <div class="main">
                        <div class="col-main">
                            <div class ='std'>
                                <p><h1>{{nome}}</h1></p>
                                <div id="editor" autofocus></div>
                                <button type="button" id="delete" onclick="cancella()">Cancella Documento</button>
                                <button type="button" id="leave" onclick="leave()">Chiudi Documento</button>
                                <button type="button" id="export" onclick='download()'>Esporta Documento</button>
                                <button type="button" id="save" onclick="salva()">Salva</button>
                                <h1>Importa Documento</h1>
                                <div>
                                    Seleziona un file .txt: 
                                    <input type="file" id="fileInput">
                                </div>
                                <pre id="fileDisplayArea"></pre>  
                            </div>
                        </div>
                    </div>
                </div>
                <div class="footer-container">
                    <div class="footer">
                        <address>Copyright 2013 Pad company.</address>
                    </div>
                </div>
            </div>     
        </div>
        <script src="http://ajaxorg.github.com/ace/build/src/ace.js"></script>
        <script src="/channel/bcsocket.js"></script>
        <script src="/share/share.uncompressed.js"></script>
        <script>
            var editor = ace.edit("editor");
            var documento;
            function listener(msg) {
                if (msg == 'CHIUDERE'){
                    documento.emit('exit');
                };
            };

            function callback() {
                documento.close();
                var f = document.createElement("form");
                    f.method='post';
                    f.action='/delete.html';
                    f.style.visibility="hidden";

                    var i = document.createElement("input");
                    i.type='hidden';
                    i.name='titolo';
                    i.value='{{nome}}';

                    f.appendChild(i);
                    document.body.appendChild(f);
                    f.submit();
                //alert('Avresti chiuso');
            };

            sharejs.open('{{nome}}', 'text', function(error, doc) {
                doc.attach_ace(editor);
                editor.focus();

                documento=doc;
                documento.on('shout', listener);
            });

            function cancella() {
                    if ((confirm('Cancellare il documento???\nATTENZIONE: i dati saranno "IRRIMEDIABILMENTE" persi.'))) {
                        //documento.shout('CHIUDERE');
                        /*documento.removeListener('shout', listener);*/
                        documento.exit(callback);
                        //console.warn(listener);
                    }
                };

            function leave() {
                documento.close();
                location.href = "/";
            };

            function download() {
                var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
                documento.save( function(){
                    //if per risolvere il bug di chrome....ricordarsi di abilitare i popup se si usa chrome
                    if (is_chrome) {
                        //var myWindow = window.open("/export?file={{nome}}","_blank","toolbar=yes, width=500, height=100");
                        window.open('/export?file={{nome}}','mywindow','width=500,height=200,toolbar=yes, location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes')
                        //myWindow.document.write("<p>Pagina di Download!</p>");
                    }
                    else  {
                        var f = document.createElement("form");
                        f.method='get';
                        f.action='/export';
                        f.style.visibility="hidden";

                        var i = document.createElement("input");
                        i.type='hidden';
                        i.name='file';
                        i.value='{{nome}}';

                        f.appendChild(i);
                        document.body.appendChild(f);
                        f.submit();
                    }
                });
            };
            window.onload = function() {
                var fileInput = document.getElementById('fileInput');
                var fileDisplayArea = document.getElementById('fileDisplayArea');
                fileInput.value='';

                fileInput.addEventListener('change', function(evt) {
                    var file = fileInput.files[0];
                    var textType = /text.*/;

                    if (file.type.match(textType)) {
                        var reader = new FileReader();      
                        reader.readAsText(file, "UTF-8");

                        function updateProgress(evt) {
                            if (evt.lengthComputable) {
                                var loaded = (evt.loaded / evt.total);
                                if (loaded < 1) {
                                    document.getElementById('fileInput').textContent = "caricato il " + loaded +"%";
                                }
                            }
                        };

                        function loaded(evt) {  
                            var fileString = evt.target.result;
                            editor.getSession().setValue(fileString);
                            document.getElementById('fileInput').value="";
                            editor.focus();
                        };

                        function errorHandler(evt) {
                            if(evt.target.error.name == "NOT_READABLE_ERR") {
                                document.getElementById('fileInput').textContent = "si è verificato un errore nel caricamento";
                                document.getElementById('fileInput').value="";
                            }
                        };
                        reader.onprogress = updateProgress;
                        reader.onload = loaded;
                        reader.onerror = errorHandler;

                    } 
                    else {
                        fileDisplayArea.innerText = "Il file deve essere .txt";
                        document.getElementById('fileInput').value="";
                    }
                });
            }

            function salva(){
                documento.save(function(){
                    alert('documento salvato');
                });
            }
        </script>
        <script src="/share/ace.js"></script>
	</body>
</html>